package fr.castorhoz.isi_connectivity_widget;

import java.util.ArrayList;
import java.util.List;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import fr.castorhoz.isi_connectivity_widget.BluetoothWidget.BluetoothButton;
import fr.castorhoz.isi_connectivity_widget.GPSWidget.GPSButton;
import fr.castorhoz.isi_connectivity_widget.WifiWidget.WifiButton;

public class ConnWidget extends AppWidgetProvider {
	private static List<ConnButton> listButtons = new ArrayList<ConnButton>();
	private static boolean isFirst = true;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		Log.i(this.getClass().toString(), "onUpdate ConnWidget");

		if (isFirst) {
			listButtons = new ArrayList<ConnButton>();
			listButtons.add(new WifiButton(context));
			listButtons.add(new GPSButton(context));
			listButtons.add(new BluetoothButton(context));
			isFirst = false;
		}

		for (int i = 0; i < appWidgetIds.length; i++) {
			int appWidgetId = appWidgetIds[i];
			updateAppWidget(context, appWidgetManager, appWidgetId);
		}

		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

	private void updateAppWidget(Context context,
			AppWidgetManager appWidgetManager, int appWidgetId) {
		Log.i(this.getClass().toString(), "Update Appwidget");

		// remote views
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		// update image of wifi
		for (ConnButton but : listButtons) {
			Intent intent = new Intent(context, ConnWidget.class);
			intent.setAction(but.getAction());
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
					0, intent, 0);
			remoteViews
					.setOnClickPendingIntent(but.getIdButton(), pendingIntent);
		}

		appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		System.gc();
		Log.i(this.getClass().toString(), "on receive connWidget action = " + intent.getAction());
		
		for(ConnButton but : listButtons)
		{
			if (intent.getAction().equals(but.getAction())){
				Log.i(this.getClass().toString(), "switch network!");
				but.switchNetwork(context);
			}
			
		}
		
		super.onReceive(context, intent);
	}

}
